<template>
  <div>
    <h1>WebSocket示例</h1>
    <button @click="connect">连接WebSocket</button>
    <button @click="disconnect">断开WebSocket</button>
    <div v-if="connected">
      <input type="text" v-model="message" placeholder="输入消息" />
      <button @click="sendMessage">发送消息</button>
    </div>
    <div v-for="msg in messages" :key="msg.id">{{ msg.text }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      connected: false,
      message: "",
      messages: [],
    };
  },
  methods: {
    connect() {
      this.socket = new WebSocket("ws://82.157.123.54:9010/ajaxchattest"); // 替换成实际的WebSocket服务器地址
      this.socket.onopen = () => {
        this.connected = true;
        console.log("WebSocket已连接");
      };
      this.socket.onmessage = (event) => {
        this.messages.push({ id: Date.now(), text: event.data });
        console.log("收到消息:", event.data);
      };
      this.socket.onclose = () => {
        this.connected = false;
        console.log("WebSocket已关闭");
      };
    },
    disconnect() {
      if (this.socket) {
        this.socket.close();
      }
    },
    sendMessage() {
      if (this.socket && this.message) {
        this.socket.send(this.message);
        this.message = "";
      }
    },
  },
};
</script>
